# Build file for the native C extension.
#
# = Environment variables
#
# CFLAGS        :: Override the default options passed to the compiler.
# CFLAGS_EXTRA  :: Provide additional options for the compiler.
# LDFLAGS       :: Override the default options passed to the linker.
# LDFLAGS_EXTRA :: Provide additional options for the linker.
# SIMULATOR     :: ID of the simulator.
#
#--
# Copyright 2006 Suraj N. Kurapati
# See the file named LICENSE for details.

require 'rake/clean'
require 'rbconfig'

$:.unshift File.join(File.dirname(__FILE__), '..', 'lib')
require 'ruby-vpi/rake'


desc "Builds the extension."
task :default => 'Makefile' do |t|
  sh 'make', '-f', t.prerequisites[0]
end

file 'Makefile' => [:swig, 'extconf.rb'] do |t|
  args = []

  if flags = ENV['CFLAGS']
    args << "--with-cflags=#{flags}"
  end

  if flags = ENV['LDFLAGS']
    args << "--with-ldflags=#{flags}"
  end

  ruby t.prerequisites[1], *args
end

CLEAN.include 'Makefile', 'mkmf.log', '*.o', "*.#{Config::CONFIG['DLEXT']}"


desc 'Generate Ruby wrapper for VPI.'
task :swig => 'swig.cin'

file 'swig.cin' => 'swig_vpi.i' do |t|
  sh %w[swig -Werror -w801 -ruby -o], t.name, t.prerequisites[0]
end

file 'swig_vpi.i' => 'swig_vpi.h'

# create a custom version of the standard vpi_user.h file to
# accomodate quirks in C compilers and Verilog simulators
file 'swig_vpi.h' => 'vpi_user.h' do |t|
  src, dst = t.prerequisites[0], t.name

  File.open(dst, 'w') do |f|
    input = File.read(src)

    # this is only relevant for the C language VPI interface
    input.gsub! %r{^.*vlog_startup_routines.*$}, ''

    # avoid compilation errors due to va_list, which is used
    # in the SWIG-generated wrapper for VPI vprintf functions
    input.gsub! %r{\bva_list\b}, 'void*'

    # VCS does not load the Ruby-VPI shared object file if it contains
    # references to the vpi_put_data and vpi_get_data symbols
    if ENV['SIMULATOR'] == 'vcs'
      input.gsub! %r{^.*vpi_(get|put)_data[^;]+;}, ''
    end

    f << input
  end
end

CLEAN.include 'swig.cin', 'swig_vpi.h'
